package com.welink.cmp.meatdata.importdata;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSONObject;
import com.welink.base.exception.BizException;
import com.welink.cmp.convertor.GenericConvertor;
import com.welink.cmp.domain.metadata.Router;
import com.welink.cmp.domain.metadata.gateway.IRouterGateway;
import com.welink.cmp.meatdata.command.HostCmdExe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yanwei li create  2024-06-24 11:27
 */
@Service
@Slf4j
public class RouterExcelListener implements ReadListener<RouterExcelColumn> {

    @Autowired
    private IRouterGateway routerGateway;

    @Autowired
    private HostCmdExe hostCmdExe;

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<RouterExcelColumn> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(RouterExcelColumn data, AnalysisContext context) {
        log.info("解析到一条防火墙 firewall 数据:{}", JSONObject.toJSONString(data));
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());

        List<Router> routerList = GenericConvertor.toDOList(cachedDataList, Router.class);
        final Boolean b = routerGateway.saveOrUpdateBatchBySn(routerList);
        if (b){
            log.info("存储数据库成功！");
        }else{
            throw new BizException("导入防火墙数据失败，异常数据列表{"+ JSONObject.toJSONString(cachedDataList) +"}") ;
        }
    }
}
